package com.coc.core.security.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.coc.core.jwt.JwtTokenUtil;
import com.coc.core.utils.JudgeResUtil;
import com.coc.core.redis.RedisOptCacheUtils;
import com.coc.entity.core.JsonResult;
import com.coc.entity.core.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: songju
 * @Description: 登出成功处理逻辑
 * @Date Create in 2019/9/4
 */
@Component

public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    RedisOptCacheUtils redisUtils;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String authHeader = httpServletRequest.getHeader("Authorization");
        if (StrUtil.isNotBlank(authHeader)){
            String authToken = authHeader.substring("Bearer ".length());
            String username = JwtTokenUtil.parseToken(authToken, "_secret");
            boolean b = JudgeResUtil.JudgeIsMoblie(httpServletRequest);
            //删除该键,实现手机和电脑均是单点登录
            if (b){//手机端
                redisUtils.delete("mobile_"+username);
            }else {
                redisUtils.delete("computer_"+username);
            }
        }
        JsonResult result = ResultTool.success();
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
